import os
from typing import Optional

from PyQt5.QtCore import Qt, QPoint, QThread, pyqtSignal, QObject
from PyQt5.QtGui import QMovie, QPainter
from PyQt5.QtWidgets import QLabel, QDialog, QVBoxLayout, QWidget

from logAgent.logManager import Loger


class WaitWidget(QLabel):
    def __init__(self, parent=None):
        super(WaitWidget, self).__init__(parent=parent)
        self.movie_obj = None
        self.setScaledContents(True)
        self.setAlignment(Qt.AlignCenter)

    def setGif(self, gif_path):
        self.movie_obj = QMovie(gif_path)
        #self.movie_obj.currentPixmap().
        self.setMovie(self.movie_obj)
        self.movie_obj.start()

    def paintEvent(self, event):
        # 重写动画的绘制事件，使用自带的会导致动画模糊有锯齿
        if self.movie_obj and self.movie_obj.isValid():
            painter = QPainter(self)
            painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
            curr_pix = self.movie_obj.currentPixmap()
            if self.hasScaledContents():
                pix = curr_pix.scaled(self.size(), Qt.AspectRatioMode.IgnoreAspectRatio,
                                      Qt.TransformationMode.SmoothTransformation)
                painter.drawPixmap(QPoint(0, 0), pix)
            else:
                painter.drawPixmap(QPoint(0, 0), curr_pix)
        else:
            super().paintEvent(event)


class WaitDialog(QDialog):
    __imgWidget = None

    def __init__(self, imgPath: Optional[str] = None, parent: Optional[QWidget] = None):
        super(WaitDialog, self).__init__(parent=parent)
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint)
        vb = QVBoxLayout()
        vb.setContentsMargins(0,0,0,0)
        current_path = os.path.abspath(__file__)
        current_path = os.path.dirname(current_path)
        current_path = os.path.dirname(current_path)
        print(current_path)
        self.__imgWidget = WaitWidget()
        if imgPath is None:
            self.__imgWidget.setGif(f'{current_path}\\images\\wait.gif')
        else:
            self.__imgWidget.setGif(imgPath)
        vb.addWidget(self.__imgWidget)
        self.setLayout(vb)


class WaitDialogWorker(QThread):
    __finished = pyqtSignal()
    __cbFunc = None

    def __init__(self, callbackFunc, imgPath: Optional[str] = None, parent: Optional[QObject] = None):
        super(WaitDialogWorker, self).__init__(parent)
        self.__cbFunc = callbackFunc
        self.__dialog = WaitDialog(imgPath)
        self.__finished.connect(self.__dialog.accept)

    def run(self):
        #Loger.GetSingleton().msg('begin wait dialog')
        if self.__cbFunc is not None:
            self.__cbFunc()
        else:
            self.sleep(2)
            print('!!!! please set call back function first.')
        # 完成后发出信号
        #Loger.GetSingleton().msg('end wait dialog')
        self.__finished.emit()

    def start(self, priority = ...):
        super().start()
        self.__dialog.exec_()

if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication
    import sys
    app = QApplication(sys.argv)
    # dialog = WaitDialog()
    # dialog.resize(500, 500)
    # dialog.show()
    w = WaitDialogWorker(None)
    w.start()
    sys.exit(app.exec_())